package wviper

import (
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)
const (
	ReadPath    = "/config"
	ServiceName = "config"
)

// Binding Binding相关接口
type Binding interface {
	Bind(name string) any
}

// Reader ...
type Reader struct {
	*viper.Viper
	viperPath   string
	serviceName string
}
type Option func(*Reader)

// NewSetting 填充数据
func NewSetting(options ...Option) (*Reader, error) {
	reader := NewReader(options...)
	return reader, nil
}

func NewReader(options ...Option) *Reader {
	r := &Reader{
		Viper:       viper.New(),
		serviceName: ServiceName,
		viperPath:   ReadPath,
	}
	for _, option := range options {
		option(r)
	}
	r.AddConfigPath(r.viperPath)   //先读取用户配置地址
	r.AddConfigPath("./")          //读取默认配置
	r.AddConfigPath("../")          //读取默认配置
	r.AddConfigPath("./config")    //读取默认配置
	r.AddConfigPath("../config")   //读取默认配置
	r.SetConfigName(r.serviceName) //设置读取的文件名
	r.SetConfigType("yaml")        //设置文件的类型]
	//配置读取
	if err := r.ReadInConfig(); err != nil {
		panic(err)
	}
	r.WatchConfig()
	r.OnConfigChange(func(in fsnotify.Event) {
		r.ReadInConfig()
	})
	return r
}

func WithServiceName(name string) Option {
	return func(s *Reader) {
		s.serviceName = name
	}
}

func WithViperPath(path string) Option {
	return func(s *Reader) {
		s.viperPath = path
	}
}

// Bind ...
func (r *Reader) Bind(name string) any {
	return r.Viper.Get(name)
}
